package threadShare;

import lombok.extern.slf4j.Slf4j;

/**
 * @author： pang-yun
 * @date： 2021-10-14 17:50
 * 功能目的 ：用于  运用 面向对象的方法将  synchronized  锁  操作 作为对象 提取出来
 */

@Slf4j
public class SynchronizedPro {
    public static void main(String[] args) throws InterruptedException {
        Room room = new Room();

        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                    room.increment();
                }
            }
        };


        Thread t2 = new Thread("t1") {
            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                    room.decrement();
                }
            }
        };

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        log.info("counter: {}", room.getCounter());

    }


    // synchronized    以自身为  lock   内部实现对共享资源的保护
    static class Room {
        private int counter = 0;


        public void increment() {
            synchronized (this) {
                counter++;
            }
        }

        public void decrement() {
            synchronized (this) {
                counter--;
            }
        }

        public int getCounter() {
            synchronized (this) {
                return counter;
            }
        }
    }
}
